package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.insurance.pojo.CategoryCondition;
import com.itheima.sfbx.insurance.pojo.Condition;
import com.itheima.sfbx.insurance.mapper.ConditionMapper;
import com.itheima.sfbx.insurance.pojo.InsuranceCondition;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.IConditionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.insurance.service.IInsuranceConditionService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.sfbx.insurance.constant.ConditionCacheConstant;
import com.itheima.sfbx.insurance.dto.ConditionVO;
import com.itheima.sfbx.insurance.enums.ConditionEnum;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import lombok.extern.slf4j.Slf4j;
/**
 * @Description：筛选项服务实现类
 */
@Slf4j
@Service
public class ConditionServiceImpl extends ServiceImpl<ConditionMapper, Condition> implements IConditionService {

    @Autowired
    private IInsuranceConditionService iInsuranceConditionService;
    @Autowired
    private ICategoryConditionService categoryConditionService;

    @Override
    public Page<ConditionVO> findPage(ConditionVO conditionVO, int pageNum, int pageSize) {
        //sql：select * from safeguard where
        Page<Condition> page = lambdaQuery()
                .eq(StrUtil.isNotBlank(conditionVO.getConditionKey()),Condition::getConditionKey,conditionVO.getConditionKey())
                .like(StrUtil.isNotBlank(conditionVO.getConditionKeyName()),Condition::getConditionKeyName,conditionVO.getConditionKeyName())
                .eq(StrUtil.isNotBlank(conditionVO.getDataState()),Condition::getDataState,conditionVO.getDataState())
                .page(new Page<>(pageNum, pageSize));
        return BeanConv.toPage(page, ConditionVO.class);
    }

    @Override
    public ConditionVO findById(String conditionId) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public ConditionVO save(ConditionVO conditionVO) {
        Condition old = lambdaQuery()
                .eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .one();
        if(old!=null){
            log.error("数据key重复");
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        Condition condition = BeanConv.toBean(conditionVO, Condition.class);
        this.save(condition);
        return BeanConv.toBean(condition, ConditionVO.class);
    }

    @Override
    @Transactional
    public Boolean update(ConditionVO conditionVO) {
        //修改之前要先判断关联的冗余字段
        Condition old = getById(conditionVO.getId());
        if(old==null){
            log.error("原筛选项项不存在");
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }
        if(!StrUtil.equals(conditionVO.getConditionKey(),old.getConditionKey())){
            log.error("key不能改");
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }

        Integer count1 = iInsuranceConditionService.lambdaQuery()
                .eq(InsuranceCondition::getConditionKey, old.getConditionKey())
                .eq(InsuranceCondition::getDataState,"0")
                .count();
        Integer count2 = categoryConditionService.lambdaQuery()
                .eq(CategoryCondition::getConditionKey, old.getConditionKey())
                .eq(CategoryCondition::getDataState,"0")
                .count();
        if(count1>0||count2>0){
            log.error("已被保险或分类关联，无法修改：{}",conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }
        Condition condition = BeanConv.toBean(conditionVO,Condition.class);
        condition.setUpdateBy(null);
        condition.setUpdateTime(null);
        return this.updateById(condition);
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        List<String> ids = Arrays.asList(checkedIds);
        //先把老的查出来
        List<Condition> olds = listByIds(ids);
        if (CollUtil.isEmpty(olds)) {
            return true;
        }
        Set<String> keySet = olds.stream().map(Condition::getConditionKey).collect(Collectors.toSet());
        Integer count1 = iInsuranceConditionService.lambdaQuery()
                .in(InsuranceCondition::getConditionKey, keySet)
                .eq(InsuranceCondition::getDataState,"0")
                .count();
        Integer count2 = categoryConditionService.lambdaQuery()
                .in(CategoryCondition::getConditionKey, keySet)
                .eq(CategoryCondition::getDataState,"0")
                .count();
        if(count1>0||count2>0){
            log.error("已被保险或分类关联，无法删除：{}",keySet);
            throw new ProjectException(ConditionEnum.DEL_FAIL);
        }
        return removeByIds(ids);
    }

    @Override
    public List<ConditionVO> findList(ConditionVO conditionVO) {
        //sql：select * from safeguard where
        List<Condition> list = lambdaQuery()
                .eq(StrUtil.isNotBlank(conditionVO.getConditionKey()),Condition::getConditionKey,conditionVO.getConditionKey())
                .like(StrUtil.isNotBlank(conditionVO.getConditionKeyName()),Condition::getConditionKeyName,conditionVO.getConditionKeyName())
                .eq(StrUtil.isNotBlank(conditionVO.getDataState()),Condition::getDataState,conditionVO.getDataState())
                .list();
        return BeanConv.toBeanList(list, ConditionVO.class);
    }

    @Override
    public List<ConditionVO> findInConditionKeys(List<String> conditionKeys) {
        List<Condition> one = lambdaQuery()
                .in(Condition::getConditionKey, conditionKeys)
                .eq(Condition::getDataState, SuperConstant.DATA_STATE_0)
                .list();
        return BeanConv.toBeanList(one,ConditionVO.class);
    }
}
